package com.ft.controller;
import com.alibaba.druid.util.StringUtils;
import com.ft.config.properties.WeiXinLoginProperties;
import com.ft.utils.Code;
import com.ft.utils.HttpClientUtils;
import com.ft.utils.Result;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ft
 * @Date: 2022/10/07/17:00
 * @Description: 获取openid的接口
 */
@RestController
@RequestMapping("/wxlogin")
@CrossOrigin
public class WeiXinLoginController {
    @Autowired
    WeiXinLoginProperties wxlogin;
    @GetMapping("/{code}")
    public Result callback(@PathVariable String code){
        System.out.println ("进入到获取openid方法里："+code);
        //1.判断code是否合法
        if(StringUtils.isEmpty(code)){
            return new Result(Code.GET_ERR,"获取openid失败，code为空");
        }
        //2.通过code获取openid
        String getOpenidURL = "https://api.weixin.qq.com/sns/jscode2session?"+
                "appid="+wxlogin.getAppid()+
                "&secret="+wxlogin.getAppsecret()+
                "&js_code="+code+
                "&grant_type=authorization_code";
        String result = null;
        //2：执行请求，获取微信请求返回得数据
        try {
            result = new HttpClientUtils().get(getOpenidURL);
            // 3： 对微信返回得数据进行转换
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
            if (resultMap.get("errcode") != null) {
                return new Result(Code.GET_ERR, "微信登录出错!");
            }
            // 4: 解析微信用户得唯一凭证openid
            String openid = (String) resultMap.get("openid");
            if (org.springframework.util.StringUtils.isEmpty(openid)) {
                return new Result(Code.GET_ERR, "获取openid失败!");
            }
            // 5：封装返回
            return new Result(Code.GET_OK, openid, "获取成功!");
        }catch (Exception e) {
            return new Result(Code.GET_ERR,"获取openid失败!");
        }
    }
}
